package newcall.com.newcalldemo;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.m800.m800demos.R;
import com.m800.sdk.IM800Management;
import com.m800.sdk.M800Error;
import com.m800.sdk.M800SDK;
import com.m800.sdk.M800UserIdentity;
import com.m800.sdk.M800ValidationToken;
import com.m800.sdk.call.IM800CallSession;
import com.m800.sdk.call.M800CallSessionManager;
import com.m800.sdk.common.M800PacketError;
import com.m800.sdk.user.IM800AccountManager;
import com.m800.sdk.user.IM800UserManager;
import com.m800.sdk.user.IM800UserProfile;
import com.m800.verification.M800VerificationClient;

import static newcall.com.newcalldemo.InitM800SDKTask.DEBUG_TAG;

public class MainActivity extends AppCompatActivity {

    TextView mSearchResultTextView;
    EditText mInputPinEditText;

    private IM800Management mM800Management;
    private IM800UserManager mUserManager;
    public final static int REQUETION_CODE_LOGIN = 1001;//请求登录

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSearchResultTextView = findViewById(R.id.mSearchResultTextView);
        mInputPinEditText = findViewById(R.id.mInputPinEditText);
        mUserManager = M800SDK.getInstance().getUserManager();
        mM800Management = M800SDK.getInstance().getManagement();
        //获取权限 判断
        if (M800SDK.isInitialized())
        {

//            mM800SDK = M800SDK.getInstance();
            Log.d("test", "onCreate: 已实例化");

        } else {
//            startActivity(new Intent(this, SplashActivity.class));
//            finish();
            Log.d("test", "onCreate: 未实例化");


        }
        new NextActivityTask().execute();

    }

    public void test(View view) {
        switch (view.getId()) {
            case R.id.btn_pin:
                pin();
                break;
            case R.id.btn_random:
                randomSignUpProcess();
                break;
            case R.id.btn_uikit:
                gotoRealTime();
                break;
            case R.id.btn_reg:
                startActivity(new Intent(this, SignUpActivity.class));
                break;
            case R.id.btn_getpin:
                mGetMyPinTask.execute();
                break;
            case R.id.btn_callbyphone:
                findUserByPhone();
                break;
            case R.id.btn_Logout:
                new LogoutTask(this) {
                }.execute();
                break;
            case R.id.btn_auto:
                signUptest();
                break;
                case R.id.btn_go:
                startActivity(new Intent(this,TimeActivity.class));
                break;

        }

    }

    private void findUserByPhone() {
        String phone = ((EditText) findViewById(R.id.dt_phone)).getText().toString().trim();
        if ("".equals(phone)) return;
        M800SDK.getInstance().getUserManager().findM800UserByPhoneNumberFromServer(phone, null,
                new IM800UserManager.FindM800UserByPhoneNumberCallback() {
                    @Override
                    public void complete(String phoneNumber, IM800UserProfile userProfile, boolean isContact) {
                        if (userProfile != null) {
//                            Intent intent = new Intent(NativeContactInfoActivity.this, M800UserInfoActivity.class);
//                            intent.putExtra(M800UserInfoActivity.EXTRA_USER_PROFILE, userProfile);
//                            startActivity(intent);
                            Log.d(DEBUG_TAG, "find by phone complete: \n" + new Gson().toJson(userProfile));
                            String mJID = userProfile.getJID();
                            M800CallSessionManager.getInstance().makeOnnetCall(mJID, IM800CallSession.Media.AUDIO);

                        } else {
//                            Log.e(DEBUG_TAG, "Cannot find user by phone number " + phoneNumber);
                            Toast.makeText(MainActivity.this, "Cannot find user by phone number", Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void error(String phoneNumber, M800PacketError error, String message) {
                        Log.e(DEBUG_TAG, "Failed to find user by phone number " + phoneNumber + ", msg: " + message);
//                        new LogoutTask(getApplication()).execute();
//                        randomSignUpProcess();
                    }
                });
    }

    private void gotoRealTime() {
        IM800CallSession currentSession = M800CallSessionManager.getInstance().getCurrentCallSession();
        if (currentSession == null) {
            Intent intent = new Intent();
//            intent.setClass(this, M800MakeCallActivity.class);
            startActivity(intent);
        } else {
//            showCurrentCallScreen(currentSession);
        }
    }

    private void pin() {
        String pin = mInputPinEditText.getText().toString();
        M800SDK.getInstance().getUserManager().findM800UserByPin(pin, new IM800UserManager.FindM800UserByPinCallback() {
            @Override
            public void complete(String pin, IM800UserProfile userProfile, boolean isContact) {
                Log.d("test", "Found user with pin = " + pin + " ? " + (userProfile != null));
//                mSearchButton.setEnabled(!TextUtils.isEmpty(mInputPinEditText.getText()));
                if (userProfile != null) {
//                    mSearchResultTextView.setText(userToString(userProfile));
//                    Intent intent = new Intent(MainActivity.this, M800UserInfoActivity.class);
//                    intent.putExtra(M800UserInfoActivity.EXTRA_USER_PROFILE, userProfile);
//                    startActivity(intent);
                    String mJID = userProfile.getJID();
                    mSearchResultTextView.setText(new Gson().toJson(userProfile));
                    M800CallSessionManager.getInstance().makeOnnetCall(mJID, IM800CallSession.Media.AUDIO);

                } else {
                    mSearchResultTextView.setText("没找到");
                }
            }

            @Override
            public void error(String pin, M800PacketError error, String message) {
                Log.w("test", "Failed to search user by pin = " + pin + ", ,error msg = " + message);
//                mSearchButton.setEnabled(!TextUtils.isEmpty(mInputPinEditText.getText()));
                String errorMsg = "Error: " + message;
                mSearchResultTextView.setText(errorMsg);
            }
        });


    }




    private class NextActivityTask extends AsyncTask<Void, Void, Intent> {

        @Override
        protected Intent doInBackground(Void... voids) {
            if (M800SDK.getInstance().hasUserSignedUp()) {
                // If user has signed up, go to MainActivity
                // Connect to M800
                M800SDK.getInstance().getLifeCycleManager().applicationWillEnterForeground();
                Log.d("test", "doInBackground: 已登录了");
                return new Intent();
            } else {
                M800VerificationClient.getVerificationManager(MainActivity.this).loadPhoneNumberInfo();
                // If user hasn't sign up yet, go to SignUpActivity
                Log.d("test", "doInBackground: 未登录");
                //跳转到登录界面
                startActivityForResult(new Intent(MainActivity.this, SignUpActivity.class), REQUETION_CODE_LOGIN);
                return new Intent();
            }
        }

        @Override
        protected void onPostExecute(Intent nextActivityIntent) {
//                startActivity(nextActivityIntent);
//                finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //重新调用请求
                case REQUETION_CODE_LOGIN:
                    new NextActivityTask().execute();
                    break;
            }

        }
    }

    private AsyncTask<Void, Void, String> mGetMyPinTask = new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
            IM800AccountManager accountManager = M800SDK.getInstance().getAccountManager();
            return accountManager.getPin();
        }


        @Override
        protected void onPostExecute(String s) {
            Log.d("test", "onPostExecute: " + s);
            if (s != null && !"".equals(s)) {
                mSearchResultTextView.setText(s);

            } else {
                mSearchResultTextView.setText("获取pin 失败");
            }
        }
    };


    private void signUptest() {
//        updateViewForSignUp();

        String requestId = "15348354306035484";
        String CountryCode = "CN";
        String mInputPhoneNumber = "15761623184";
        M800UserIdentity identity = new M800UserIdentity(mInputPhoneNumber,
                CountryCode, M800UserIdentity.Type.PhoneNumber);

        mM800Management.signup(
                identity,
                requestId == null ? null : new M800ValidationToken(
                        requestId, null, M800ValidationToken.ValidationSource.M800VerificationSDK),
                IM800Management.M800Language.M800LanguageEnglish,
                new IM800Management.M800ManagementCallback() {
                    @Override
                    public void complete(boolean isSuccess, M800Error error, Bundle userInfo) {
                        Log.d(DEBUG_TAG, "M800SDK sign up complete, isSuccess = " + isSuccess);
                        if (isSuccess) {
//                            mHandler.sendEmptyMessage(MSG_SIGN_UP_SUCCESS);
                            Log.d("test", "complete: 登录成功");

                        } else {
                            //code 5 已经登录了
                            Log.d("test", "Sign up error, code = " + error.getCode() + " msg = " + error.getMessage());
//                            if("5".equals(error.getCode()+"")){
//                                mHandler.sendEmptyMessage(MSG_SIGN_UP_SUCCESS);
//                                return;
//                            }
//                            if (error.getCode() == ERROR_NEED_VERIFICATION) {
//                                mHandler.sendEmptyMessage(MSG_NEED_VERIFICATION);
//                            } else {
//                                mHandler.sendEmptyMessage(MSG_SIGN_UP_FAILED);
//                            }
                        }
//                        logSignUpEvent(isSuccess, error);
                    }
                });
    }


    private void randomSignUpProcess() {
        Long tsLong = System.currentTimeMillis() / 1000;
        String timeStamp = tsLong.toString();

        M800UserIdentity identity = new M800UserIdentity(timeStamp,
                null, M800UserIdentity.Type.SourceNetwork);
        M800SDK.getInstance().getManagement().signup(
                identity,
                null,
                IM800Management.M800Language.M800LanguageEnglish,
                new IM800Management.M800ManagementCallback() {
                    @Override
                    public void complete(boolean isSuccess, M800Error error, Bundle userInfo) {
                        Log.d("test", "M800SDK sign up complete, isSuccess = " + isSuccess);
                        if (isSuccess) {
//                            Intent intent = new Intent(IntroductionActivity.this, WelcomeActivity.class);
//                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                            startActivity(intent);
                            Toast.makeText(MainActivity.this, "随机成功首次登录", Toast.LENGTH_LONG).show();
                        } else {
                            if ("5".equals(error.getCode() + "")) {
                                Toast.makeText(MainActivity.this, "随机成功code" + error.getCode(), Toast.LENGTH_LONG).show();
                                return;
                            }
                            Log.d("test", "Sign up error, code = " + error.getCode() + " msg = " + error.getMessage());
//                            showSignUpFailedDialog("Sign up error, code = " + error.getCode() + " msg = " + error.getMessage());
                        }
//                        logSignUpEvent(isSuccess, error);
                    }
                });
    }
}
